package com.longrise.android.byjk.plugins.dealsituation.course.video2.education.webvideoedu;

import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.android.byjk.R;
import com.longrise.common.base.BasePresenter;
import com.longrise.android.byjk.event.CourseDetailEvent;
import com.longrise.android.byjk.plugins.dealsituation.course.cache.AssistCache;
import com.longrise.android.byjk.plugins.dealsituation.course.exercises.ExercisesActivity;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.defend.DefendStudy;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.dialog.UploadDialog;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.StudyRecordBase;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.ToDispatchStudy;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoConsts;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.params.VideoParams;
import com.longrise.android.byjk.plugins.dealsituation.course.video2.study.LoadVideoInfor;
import com.longrise.android.byjk.utils.DialogUtil;
import com.longrise.common.datasource.remote.LoadDataManager;
import com.longrise.common.utils.PrintLog;
import com.longrise.android.byjk.utils.Tracker_Google;


import org.greenrobot.eventbus.EventBus;

import static com.longrise.common.utils.AppUtil.getString;

/**
 * Created by godliness on 2017/8/1.
 */

public class WebVideoEduPresenter extends BasePresenter<WebVideoView> {

    private static final String TAG = "WebVideoEduPresenter";

    /**
     * 学习记录id
     */
    private String mRecordid;
    private DefendStudy mDefandStudy;
    private int mDuration;

    private UploadDialog mUploadDialog;

    /**
     * video地址
     */
    private String mVideopath;
    /**
     * web地址，可以为null或者""
     */
    private String mWebpath;
    /**
     * 课件相关状态
     */
    private StudyRecordBase.StudyState mStudyState;

    boolean upLoaded = false;

    public boolean isVideopass() {
        return mStudyState.mVideoPass;
    }

    public String videoPath() {
        return mVideopath;
    }

    public String webPath() {
        return mWebpath;
    }

    @Override
    protected void init() {
        mView.setTitle();

        mStudyState = StudyRecordBase.getStudyStateInstance();

        if (mDefandStudy == null) {
            initDefend();
        }
    }

    public void switchCwidType(String cwidType) {
        if (ToDispatchStudy.VIDEO.equals(cwidType)) {
            //横屏
            mView.setScreenOrientation(0);
        } else {
            //竖屏
            mView.setScreenOrientation(1);
        }
    }

    private void initDefend() {
        mDefandStudy = new DefendStudy(new DefendStudy.DefendStudyCallback() {
            @Override
            public StudyRecordBase.Record getRecord() {
                StudyRecordBase.Record record = genratorRecord();
                if (record == null) {
                    //不做任何执行
                    return null;
                }
                int position = mView.getCurrentPosition();
                if (position > mDuration) {
                    mDuration = mView.getDuration();
                }
                if (position > mDuration) {
                    mDuration = position;
                }
                record.mPosition = position;
                record.mDuration = mDuration;
                return record;
            }

            @Override
            public void onDefend(boolean videopass) {
                if (videopass) {
                    updateCwidState();
                }
            }

            @Override
            public void onError(int errorType) {
                grenatorUploadDialog(errorType);
            }
        });
    }

    public void reLoad() {
        toRequestResource();
    }

    public void toRefrushCourseDetail() {
        if (upLoaded) {
//            Intent courseDetailIntent = new Intent(MessageConstants.PAY_SUCCESS);
//            courseDetailIntent.putExtra(ReceiverType.RECEIVER_KEY, ReceiverType.REFRESH_DETIAL);
//            mContext.sendBroadcast(courseDetailIntent);

            CourseDetailEvent event = new CourseDetailEvent();
            event.setRefreshDetail(true);
            EventBus.getDefault().post(event);
        }
    }

    /**
     * 课后习题逻辑
     */
    public void exerciseOptions() {
        boolean hasqa = mStudyState.mHasqa;
        if (!hasqa) {
            return;
        }
        boolean finish = mStudyState.mIsFinish;
        if (finish) {
            try {
                cwidHasqaDialog(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return;
        }
        boolean videopass = mStudyState.mVideoPass;
        if (videopass) {
            try {
                cwidHasqaDialog(false);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @param duration 视频总时长
     */
    public void monitorDefendStudy(int duration) {
        this.mDuration = duration;
        if (mDefandStudy != null) {
            mDefandStudy.monitor();
        }
    }

    public void startDefendStudy() {
        if (mDefandStudy != null) {
            mDefandStudy.start();
        }
    }

    public void stopDefendStudy() {
        if (mDefandStudy != null) {
            mDefandStudy.stop();
        }
    }

    public void grenatorUploadDialog(int errorType) {
        dismissUploadDialog();
        mUploadDialog = new UploadDialog(mContext, errorType);
        mUploadDialog.setUploadInterface(new UploadDialog.DialogUploadInterface() {
            @Override
            public void onUpload() {
                mDefandStudy.manualPreformStart();
            }

            @Override
            public void back() {
                //释放资源，返回课程详情
                mView.onBack();
            }
        });
        mUploadDialog.show();
    }

    private void dismissUploadDialog() {
        if (mUploadDialog != null && mUploadDialog.isShowing()) {
            mUploadDialog.dismiss();
            mUploadDialog = null;
        }
    }

    /**
     * 加载课件资源
     */
    private void toRequestResource() {
        mView.showLoadingDialog();
        LoadVideoInfor.loadVideoPlayInfor(genratorRecord(), new LoadDataManager.OnRequestCallListener() {
            @Override
            public void onSuccess(String key, String service, Object result) {
                EntityBean resultBean = (EntityBean) result;
                if (resultBean != null) {
                    int resultState = resultBean.getInt("resultstate");
                    if (resultState != 1) {
                        mView.showToast(resultBean.getString("resultdesc"));
                        mView.error();
                        return;
                    }
                    parse(resultBean.getBean("result"));
                }
            }

            @Override
            public void onError(String key, String service, Throwable ex, boolean isOnCallback) {
                mView.error();
            }

            @Override
            public void onFinished(String key, String service) {

            }
        });
    }

    private void parse(EntityBean bean) {
        if (bean != null) {
            boolean isfinish = bean.getBoolean("isfinish");
            boolean ishasqa = bean.getBoolean("ishasqa");
            boolean isvideopass = bean.getBoolean("isvideopass");
            int position = bean.getInt("position");
            PrintLog.e(TAG, "isvideopass: " + isvideopass + "  ishasqa: " + ishasqa);
            //设置当前课件相关状态
            mStudyState.mIsFinish = isfinish;
            mStudyState.mHasqa = ishasqa;
            mStudyState.mVideoPass = isvideopass;

            mRecordid = bean.getString("recordid");
            //校验学习记录id
            if (strIsEmpty(mRecordid)) {
                mView.showToast("课件学习记录异常");
                mView.error();
                return;
            }
            mVideopath = bean.getString("videourl");
            //校验视频地址
            if (strIsEmpty(mVideopath)) {
                mView.showToast("课件配置节点异常");
                mView.error();
                return;
            }
            //视频地址不可以为null或"" ，web地址可以
            mWebpath = bean.getString("webpath");
            mView.parse(mVideopath, mWebpath, position, !(isfinish || isvideopass));
            //课后习题操作
            exerciseOptions();
        }
    }

    private boolean strIsEmpty(String str) {
        return TextUtils.isEmpty(str);
    }

    /**
     * 维护过程参数
     */
    private StudyRecordBase.Record genratorRecord() {
        VideoParams videoParams = mView.getVideoParams();
        if (videoParams != null) {
            StudyRecordBase.Record record = StudyRecordBase.getRecordInstance();
            record.mCourseid = videoParams.mCourseId;
            record.mCwid = videoParams.mCwid;
            record.mPathno = videoParams.mPathNo;
            record.mStudentno = videoParams.mStudentNo;
            record.mId = mRecordid;
            return record;
        }
        return null;
    }

    /**
     * 课后习题dialog
     */
    private void cwidHasqaDialog(boolean isFinish) throws Exception {
        if (mView.actFinished()) {
            return;
        }
        View v = View.inflate(mContext, R.layout.dialog_clearcache, null);
        final TextView textTitle = (TextView) v.findViewById(R.id.text_course_title);
        textTitle.setText(getString(R.string.videofinish_testtitle));
        final TextView textContent = (TextView) v.findViewById(R.id.text_);
        textContent.setText(isFinish ? getString(R.string.cwidfinish_testhint) : getString(R.string.videofinish_testhint));
        final TextView textCancle = (TextView) v.findViewById(R.id.text_cancle);
        textCancle.setText(getString(R.string.videofinish_testcancle));
        final TextView textConfrim = (TextView) v.findViewById(R.id.text_confirm);
        textConfrim.setText(isFinish ? getString(R.string.videofinish_testshow) : getString(R.string.videofinish_testconfrim));
        View.OnClickListener mOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogUtil.getInstance().dismiss();
                switch (v.getId()) {
                    case R.id.text_cancle:
                        Tracker_Google.getInstance().addEvent("Excercise-after", "Next-time", "下次再说");
                        break;
                    case R.id.text_confirm:
                        toHasqaActivity();
                        Tracker_Google.getInstance().addEvent("Excercise-after", "do-now", "立即做题");
                        break;
                    default:
                        break;
                }
            }
        };
        textConfrim.setOnClickListener(mOnClickListener);
        textCancle.setOnClickListener(mOnClickListener);
        DialogUtil.getInstance().creatAlertDialog(mContext, v, 266, 171);
    }

    /**
     * 打开习题
     */
    private void toHasqaActivity() {
        VideoParams videoParams = mView.getVideoParams();
        if (videoParams == null) {
            return;
        }
        Intent intent = new Intent(mContext, ExercisesActivity.class);
        intent.putExtra(VideoConsts.VIDEO_PARAMS_PARCELABLE, videoParams);
        mContext.startActivity(intent);
        mView.onBack();
    }

    /**
     * 通知课程详情页，刷新数据
     * 如果课件本身是已通过状态将不发送消息更新状态
     * 如果课件有课后习题，更新状态在课后习题界面
     * <p>
     * 如果无课后习题, videopass == true, 那isFinsh也等于true 在播放之前课件已经为通过状态，
     * 如果无课后习题, videopass == false, 更新课件学习状态
     * 只要有课后习题存在，isFinish == false, 更新课件状态在课后习题页面
     */
    private void updateCwidState() {
        boolean videoPass = mStudyState.mVideoPass;
        boolean hasqa = mStudyState.mHasqa;
        PrintLog.e(TAG, "updateCwidState videoPass: " + videoPass + "  hasqa: " + hasqa);
        if (!videoPass && !hasqa) {
            upLoaded = true;
        }
        if (upLoaded) {
            VideoParams vp = mView.getVideoParams();
            sendUpdateMessage(vp);
        }
        //必须最后更新当前课件通过状态
        mStudyState.mVideoPass = true;
        mView.setDrag(upLoaded);
    }


    private void sendUpdateMessage(VideoParams params) {
        if (params.mCwidLocal == null) {
            //如果在课程详情页进入，该值为null，不发送消息
            return;
        }
        //更新已缓存课件状态
        boolean cacheUpdated = AssistCache.updateCwidStateInCache(params.mCourseId, params.mCwidLocal);
        if (cacheUpdated) {
            //如果更新成功通知课程详情页根据索引位置更新课件状态
            CourseDetailEvent event = new CourseDetailEvent();
            event.setCoursePosition(params.mCwidLocal);
            EventBus.getDefault().post(event);

        } else {
            //如果更新失败，直接通知课程详情页toRefrush()
            CourseDetailEvent event = new CourseDetailEvent();
            event.setRefreshDetail(true);
            EventBus.getDefault().post(event);
        }
    }

}
